notebooks/community/migration/UJ6 AutoML for natural language with Vertex AI Text Classification.ipynb (2,535 lines of code) (raw):
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bLRZTKFkDdht"
},
"outputs": [],
"source": [
"# Copyright 2021 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "AKoTR-m2PmAR"
},
"source": [
"# Vertex SDK: AutoML natural language text classification model\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JE-aKjayJjkF"
},
"source": [
"## Installation\n",
"\n",
"Install the latest (preview) version of Vertex SDK."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7dxB6-B0JjkG"
},
"outputs": [],
"source": [
"! pip3 install -U google-cloud-aiplatform --user"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Iddo-8HmJjkH"
},
"source": [
"Install the Google *cloud-storage* library as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xHvi6EFSJjkH"
},
"outputs": [],
"source": [
"! pip3 install google-cloud-storage"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ktRTgB8DJjkI"
},
"source": [
"### Restart the Kernel\n",
"\n",
"Once you've installed the Vertex SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x1g4mBdlJjkI"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"if not os.getenv(\"AUTORUN\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hceMthWGJjkI"
},
"source": [
"## Before you begin\n",
"\n",
"### GPU run-time\n",
"\n",
"*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n",
"\n",
"### Set up your GCP project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n",
"\n",
"4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebooks.\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Xzde8OBYDdh2"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0UfsdLCEJjkJ"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jT0fijejJjkK"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend when possible, to choose the region closest to you. \n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You cannot use a Multi-Regional Storage bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see [Region support for Vertex AI services](https://cloud.google.com/vertex-ai/docs/general/locations)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CTBlncfrJjkK"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "J_croPBoJjkK"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KKxStk5bJjkL"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0yDWDaKwF48e"
},
"source": [
"### Authenticate your GCP account\r\n",
"\r\n",
"**If you are using Google Cloud Notebooks**, your environment is already\r\n",
"authenticated. Skip this step.\r\n",
"\r\n",
"*Note: If you are on an Vertex notebook and run the cell, the cell knows to skip executing the authentication steps.*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "HvxYUdIfGAM-"
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your Google Cloud account. This provides access\n",
"# to your Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"# If on Vertex, then don't execute this code\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this tutorial in a notebook locally, replace the string\n",
" # below with the path to your service account key and run this cell to\n",
" # authenticate your Google Cloud account.\n",
" else:\n",
" %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json\n",
"\n",
" # Log in to your account on Google Cloud\n",
" ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MDUAZaN3JjkL"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yU6VuylGJjkM"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QVRixM4oJjkM"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION gs://$BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Mi-Pdh6QJjkN"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aqDptKpYJjkN"
},
"outputs": [],
"source": [
"! gsutil ls -al gs://$BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fR9geV9pJjkO"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hIHTX-pkJjkO"
},
"source": [
"#### Import Vertex SDK\n",
"\n",
"Import the Vertex SDK into our Python environment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qrSkIKVgJjkO"
},
"outputs": [],
"source": [
"import base64\n",
"import json\n",
"import os\n",
"import sys\n",
"import time\n",
"\n",
"from google.cloud.aiplatform import gapic as aip\n",
"from google.protobuf import json_format\n",
"from google.protobuf.json_format import MessageToJson, ParseDict\n",
"from google.protobuf.struct_pb2 import Struct, Value"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lbv411XjJjkP"
},
"source": [
"#### Vertex AI constants\n",
"\n",
"Setup up the following constants for Vertex AI:\n",
"\n",
"- `API_ENDPOINT`: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.\n",
"- `PARENT`: The Vertex AI location root path for dataset, model and endpoint resources."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Gx8Eos8PJjkP"
},
"outputs": [],
"source": [
"# API Endpoint\n",
"API_ENDPOINT = \"{}-aiplatform.googleapis.com\".format(REGION)\n",
"\n",
"# Vertex AI location root path for your dataset, model and endpoint resources\n",
"PARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4x_t-MWnJjkQ"
},
"source": [
"#### AutoML constants\n",
"\n",
"Next, setup constants unique to AutoML Text Classification datasets and training:\n",
"\n",
"- Dataset Schemas: Tells the managed dataset service which type of dataset it is.\n",
"- Data Labeling (Annotations) Schemas: Tells the managed dataset service how the data is labeled (annotated).\n",
"- Dataset Training Schemas: Tells the Vertex AI Pipelines service the task (e.g., classification) to train the model for."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nmzhH42tJjkQ"
},
"outputs": [],
"source": [
"# Text Dataset type\n",
"TEXT_SCHEMA = \"google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml\"\n",
"# Text Labeling type\n",
"IMPORT_SCHEMA_TEXT_CLASSIFICATION = \"gs://google-cloud-aiplatform/schema/dataset/ioformat/text_classification_single_label_io_format_1.0.0.yaml\"\n",
"# Text Training task\n",
"TRAINING_TEXT_CLASSIFICATION_SCHEMA = \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_classification_1.0.0.yaml\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "R7P3MRNgJjkQ"
},
"source": [
"## Clients Vertex AI\n",
"\n",
"The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).\n",
"\n",
"You will use several clients in this tutorial, so set them all up upfront.\n",
"\n",
"- Dataset Service for managed datasets.\n",
"- Model Service for managed models.\n",
"- Pipeline Service for training.\n",
"- Endpoint Service for deployment.\n",
"- Prediction Service for serving. *Note*: Prediction has a different service endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kt8j_ey4JjkR"
},
"outputs": [],
"source": [
"# client options same for all services\n",
"client_options = {\"api_endpoint\": API_ENDPOINT}\n",
"\n",
"\n",
"def create_dataset_client():\n",
" client = aip.DatasetServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_model_client():\n",
" client = aip.ModelServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_pipeline_client():\n",
" client = aip.PipelineServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_endpoint_client():\n",
" client = aip.EndpointServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_prediction_client():\n",
" client = aip.PredictionServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_job_client():\n",
" client = aip.JobServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"clients = {}\n",
"clients[\"dataset\"] = create_dataset_client()\n",
"clients[\"model\"] = create_model_client()\n",
"clients[\"pipeline\"] = create_pipeline_client()\n",
"clients[\"endpoint\"] = create_endpoint_client()\n",
"clients[\"prediction\"] = create_prediction_client()\n",
"clients[\"job\"] = create_job_client()\n",
"\n",
"for client in clients.items():\n",
" print(client)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Ii4kquRRPmAn"
},
"outputs": [],
"source": [
"IMPORT_FILE = \"gs://cloud-ml-data/NL-classification/happiness.csv\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ATVQWpgnPmAo"
},
"outputs": [],
"source": [
"! gsutil cat $IMPORT_FILE | head -n 10"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "endpoints_undeploymodel:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"I went on a successful date with someone I felt sympathy and connection with.,affection\n",
"I was happy when my son got 90% marks in his examination,affection\n",
"I went to the gym this morning and did yoga.,exercise\n",
"We had a serious talk with some friends of ours who have been flaky lately. They understood and we had a good evening hanging out.,bonding\n",
"I went with grandchildren to butterfly display at Crohn Conservatory,affection\n",
"I meditated last night.,leisure\n",
"\"I made a new recipe for peasant bread, and it came out spectacular!\",achievement\n",
"I got gift from my elder brother which was really surprising me,affection\n",
"YESTERDAY MY MOMS BIRTHDAY SO I ENJOYED,enjoy_the_moment\n",
"Watching cupcake wars with my three teen children,affection\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_create_dataset:migration"
},
"source": [
"## Create a dataset"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_datasets_create:migration,new"
},
"source": [
"### [projects.locations.datasets.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.datasets/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "L9TCLZcqDdh-"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LV0CGdWxDdh-"
},
"outputs": [],
"source": [
"DATA_SCHEMA = TEXT_SCHEMA\n",
"\n",
"dataset = {\n",
" \"display_name\": \"happiness_\" + TIMESTAMP,\n",
" \"metadata_schema_uri\": \"gs://\" + DATA_SCHEMA,\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oW46N7zDPmAq"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"dataset\": {\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"metadataSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "46JjhmPfDdh_"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Opc77NQcDdh_"
},
"outputs": [],
"source": [
"request = clients[\"dataset\"].create_dataset(parent=PARENT, dataset=dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6rltMZbbDdh_"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "zIJgoVVpDdh_"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1EbxR8zZPmAt"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/datasets/574578388396670976\",\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"metadataSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml\",\n",
" \"labels\": {\n",
" \"aiplatform.googleapis.com/dataset_metadata_schema\": \"TEXT\"\n",
" },\n",
" \"metadata\": {\n",
" \"dataItemSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/dataitem/text_1.0.0.yaml\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GiCxvMfDPmAu"
},
"outputs": [],
"source": [
"# The full unique ID for the dataset\n",
"dataset_id = result.name\n",
"# The short numeric ID for the dataset\n",
"dataset_short_id = dataset_id.split(\"/\")[-1]\n",
"\n",
"print(dataset_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_datasets_import:migration,new"
},
"source": [
"### [projects.locations.datasets.import](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.datasets/import)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rTHSmwyHDdh_"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bt8QqcrQDdiA"
},
"outputs": [],
"source": [
"LABEL_SCHEMA = IMPORT_SCHEMA_TEXT_CLASSIFICATION\n",
"\n",
"import_config = {\n",
" \"gcs_source\": {\"uris\": [IMPORT_FILE]},\n",
" \"import_schema_uri\": LABEL_SCHEMA,\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.ImportDataRequest(\n",
" name=dataset_short_id, import_configs=[import_config]\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Jjzp5G2QPmAw"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"574578388396670976\",\n",
" \"importConfigs\": [\n",
" {\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://cloud-ml-data/NL-classification/happiness.csv\"\n",
" ]\n",
" },\n",
" \"importSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/ioformat/text_classification_single_label_io_format_1.0.0.yaml\"\n",
" }\n",
" ]\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BuJAHvs4DdiA"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XccT_J1CDdiA"
},
"outputs": [],
"source": [
"request = clients[\"dataset\"].import_data(\n",
" name=dataset_id, import_configs=[import_config]\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bh6rq24uDdiA"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "skZIZaulDdiA"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "drQ196C7PmA0"
},
"source": [
"*Example output*:\n",
"```\n",
"{}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_create_and_deploy_model:migration"
},
"source": [
"## Train a model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0oqIBOSnJjkW"
},
"source": [
"### [projects.locations.trainingPipelines.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.trainingPipelines/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6TEExyzrDdiB"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IqU_AskkDdiB"
},
"outputs": [],
"source": [
"TRAINING_SCHEMA = TRAINING_TEXT_CLASSIFICATION_SCHEMA\n",
"\n",
"task = json_format.ParseDict(\n",
" {\n",
" \"multi_label\": False,\n",
" },\n",
" Value(),\n",
")\n",
"\n",
"training_pipeline = {\n",
" \"display_name\": \"happiness_\" + TIMESTAMP,\n",
" \"input_data_config\": {\"dataset_id\": dataset_short_id},\n",
" \"model_to_upload\": {\"display_name\": \"happiness_\" + TIMESTAMP},\n",
" \"training_task_definition\": TRAINING_SCHEMA,\n",
" \"training_task_inputs\": task,\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateTrainingPipelineRequest(\n",
" parent=PARENT, training_pipeline=training_pipeline\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FRJplFjTPmA2"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"trainingPipeline\": {\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"inputDataConfig\": {\n",
" \"datasetId\": \"574578388396670976\"\n",
" },\n",
" \"trainingTaskDefinition\": \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_classification_1.0.0.yaml\",\n",
" \"trainingTaskInputs\": {\n",
" \"multi_label\": false\n",
" },\n",
" \"modelToUpload\": {\n",
" \"displayName\": \"happiness_20210226015238\"\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "VeO6x5u6DdiC"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "oehjkwElDdiC"
},
"outputs": [],
"source": [
"request = clients[\"pipeline\"].create_training_pipeline(\n",
" parent=PARENT, training_pipeline=training_pipeline\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b6D1PnMUDdiC"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qbwBVg9NDdiC"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qJY27GO1PmA3"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/trainingPipelines/2903115317607661568\",\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"inputDataConfig\": {\n",
" \"datasetId\": \"574578388396670976\"\n",
" },\n",
" \"trainingTaskDefinition\": \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_classification_1.0.0.yaml\",\n",
" \"trainingTaskInputs\": {},\n",
" \"modelToUpload\": {\n",
" \"displayName\": \"happiness_20210226015238\"\n",
" },\n",
" \"state\": \"PIPELINE_STATE_PENDING\",\n",
" \"createTime\": \"2021-02-26T02:23:54.166560Z\",\n",
" \"updateTime\": \"2021-02-26T02:23:54.166560Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "R3dVRAJ2PmA4"
},
"outputs": [],
"source": [
"# The full unique ID for the training pipeline\n",
"training_pipeline_id = request.name\n",
"# The short numeric ID for the training pipeline\n",
"training_pipeline_short_id = training_pipeline_id.split(\"/\")[-1]\n",
"\n",
"print(training_pipeline_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QJsV1xoSJjkW"
},
"source": [
"### [projects.locations.trainingPipelines.get](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.trainingPipelines/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jMx7wPO4DdiC"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nkSMNyEHDdiD"
},
"outputs": [],
"source": [
"request = clients[\"pipeline\"].get_training_pipeline(name=training_pipeline_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bnn0DVfVDdiD"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RxwZkKHHDdiD"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "W3vyjjnIPmA6"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/trainingPipelines/2903115317607661568\",\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"inputDataConfig\": {\n",
" \"datasetId\": \"574578388396670976\"\n",
" },\n",
" \"trainingTaskDefinition\": \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_classification_1.0.0.yaml\",\n",
" \"trainingTaskInputs\": {},\n",
" \"modelToUpload\": {\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/2369051733671280640\",\n",
" \"displayName\": \"happiness_20210226015238\"\n",
" },\n",
" \"state\": \"PIPELINE_STATE_SUCCEEDED\",\n",
" \"createTime\": \"2021-02-26T02:23:54.166560Z\",\n",
" \"startTime\": \"2021-02-26T02:23:54.396088Z\",\n",
" \"endTime\": \"2021-02-26T06:08:06.548524Z\",\n",
" \"updateTime\": \"2021-02-26T06:08:06.548524Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "trainingpipelines_get:migration,new,wait"
},
"outputs": [],
"source": [
"while True:\n",
" response = clients[\"pipeline\"].get_training_pipeline(name=training_pipeline_id)\n",
" if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:\n",
" print(\"Training job has not completed:\", response.state)\n",
" model_to_deploy_name = None\n",
" if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:\n",
" break\n",
" else:\n",
" model_id = response.model_to_upload.name\n",
" print(\"Training Time:\", response.end_time - response.start_time)\n",
" break\n",
" time.sleep(20)\n",
"\n",
"print(model_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_evaluate_the_model:migration"
},
"source": [
"## Evaluate the model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BJNzhELXJjkY"
},
"source": [
"### [projects.locations.models.evaluations.list](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.models.evaluations/list)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "--qyaaviDdiG"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "q5c2I_oFDdiH"
},
"outputs": [],
"source": [
"request = clients[\"model\"].list_model_evaluations(parent=model_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "njIDMGb0DdiH"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "y0wUwEgUDdiH"
},
"outputs": [],
"source": [
"model_evaluations = [json.loads(MessageToJson(mel.__dict__[\"_pb\"])) for mel in request]\n",
"\n",
"print(json.dumps(model_evaluations, indent=2))\n",
"\n",
"# The evaluation slice\n",
"evaluation_slice = request.model_evaluations[0].name"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0RsA8RqKPmA-"
},
"source": [
"*Example output*:\n",
"```\n",
"[\n",
" {\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/2369051733671280640/evaluations/1541152463304785920\",\n",
" \"metricsSchemaUri\": \"gs://google-cloud-aiplatform/schema/modelevaluation/classification_metrics_1.0.0.yaml\",\n",
" \"metrics\": {\n",
" \"confusionMatrix\": {\n",
" \"annotationSpecs\": [\n",
" {\n",
" \"displayName\": \"exercise\",\n",
" \"id\": \"952213353537732608\"\n",
" },\n",
" {\n",
" \"id\": \"1528674105841156096\",\n",
" \"displayName\": \"achievement\"\n",
" },\n",
" {\n",
" \"id\": \"3258056362751426560\",\n",
" \"displayName\": \"leisure\"\n",
" },\n",
" {\n",
" \"id\": \"3834517115054850048\",\n",
" \"displayName\": \"bonding\"\n",
" },\n",
" {\n",
" \"id\": \"5563899371965120512\",\n",
" \"displayName\": \"enjoy_the_moment\"\n",
" },\n",
" {\n",
" \"id\": \"6140360124268544000\",\n",
" \"displayName\": \"nature\"\n",
" },\n",
" {\n",
" \"id\": \"8446203133482237952\",\n",
" \"displayName\": \"affection\"\n",
" }\n",
" ],\n",
" \"rows\": [\n",
" [\n",
" 19.0,\n",
" 1.0,\n",
" 0.0,\n",
" 0.0,\n",
" 0.0,\n",
" 0.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 342.0,\n",
" 5.0,\n",
" 2.0,\n",
" 13.0,\n",
" 2.0,\n",
" 13.0\n",
" ],\n",
" [\n",
" 2.0,\n",
" 10.0,\n",
" 42.0,\n",
" 1.0,\n",
" 12.0,\n",
" 0.0,\n",
" 2.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 4.0,\n",
" 0.0,\n",
" 121.0,\n",
" 1.0,\n",
" 0.0,\n",
" 4.0\n",
" ],\n",
" [\n",
" 2.0,\n",
" 29.0,\n",
" 3.0,\n",
" 2.0,\n",
" 98.0,\n",
" 0.0,\n",
" 6.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 3.0,\n",
" 0.0,\n",
" 1.0,\n",
" 0.0,\n",
" 21.0,\n",
" 1.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 7.0,\n",
" 0.0,\n",
" 1.0,\n",
" 6.0,\n",
" 0.0,\n",
" 409.0\n",
" ]\n",
" ]\n",
" },\n",
" \"confidenceMetrics\": [\n",
" {\n",
" \"f1Score\": 0.25,\n",
" \"recall\": 1.0,\n",
" \"f1ScoreAt1\": 0.88776374,\n",
" \"precisionAt1\": 0.88776374,\n",
" \"precision\": 0.14285715,\n",
" \"recallAt1\": 0.88776374\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 0.05,\n",
" \"recall\": 0.9721519,\n",
" \"f1Score\": 0.8101266,\n",
" \"recallAt1\": 0.88776374,\n",
" \"f1ScoreAt1\": 0.88776374,\n",
" \"precisionAt1\": 0.88776374,\n",
" \"precision\": 0.69439423\n",
" },\n",
" \n",
" # REMOVED FOR BREVITY\n",
" \n",
" {\n",
" \"f1Score\": 0.0033698399,\n",
" \"recall\": 0.0016877637,\n",
" \"confidenceThreshold\": 1.0,\n",
" \"recallAt1\": 0.0016877637,\n",
" \"f1ScoreAt1\": 0.0033698399,\n",
" \"precisionAt1\": 1.0,\n",
" \"precision\": 1.0\n",
" }\n",
" ],\n",
" \"auPrc\": 0.95903283,\n",
" \"logLoss\": 0.08260541\n",
" },\n",
" \"createTime\": \"2021-02-26T06:07:48.967028Z\",\n",
" \"sliceDimensions\": [\n",
" \"annotationSpec\"\n",
" ]\n",
" }\n",
"]\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wr2JuU5nJjka"
},
"source": [
"### [projects.locations.models.evaluations.get](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.models.evaluations/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "edJ4XjSbDdiI"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8R-P7LzdDdiI"
},
"outputs": [],
"source": [
"request = clients[\"model\"].get_model_evaluation(name=evaluation_slice)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nyTwMNrmDdiI"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wj_LtYzJDdiI"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cjAR1CVDPmBB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/2369051733671280640/evaluations/1541152463304785920\",\n",
" \"metricsSchemaUri\": \"gs://google-cloud-aiplatform/schema/modelevaluation/classification_metrics_1.0.0.yaml\",\n",
" \"metrics\": {\n",
" \"confusionMatrix\": {\n",
" \"annotationSpecs\": [\n",
" {\n",
" \"displayName\": \"exercise\",\n",
" \"id\": \"952213353537732608\"\n",
" },\n",
" {\n",
" \"displayName\": \"achievement\",\n",
" \"id\": \"1528674105841156096\"\n",
" },\n",
" {\n",
" \"id\": \"3258056362751426560\",\n",
" \"displayName\": \"leisure\"\n",
" },\n",
" {\n",
" \"id\": \"3834517115054850048\",\n",
" \"displayName\": \"bonding\"\n",
" },\n",
" {\n",
" \"displayName\": \"enjoy_the_moment\",\n",
" \"id\": \"5563899371965120512\"\n",
" },\n",
" {\n",
" \"displayName\": \"nature\",\n",
" \"id\": \"6140360124268544000\"\n",
" },\n",
" {\n",
" \"id\": \"8446203133482237952\",\n",
" \"displayName\": \"affection\"\n",
" }\n",
" ],\n",
" \"rows\": [\n",
" [\n",
" 19.0,\n",
" 1.0,\n",
" 0.0,\n",
" 0.0,\n",
" 0.0,\n",
" 0.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 342.0,\n",
" 5.0,\n",
" 2.0,\n",
" 13.0,\n",
" 2.0,\n",
" 13.0\n",
" ],\n",
" [\n",
" 2.0,\n",
" 10.0,\n",
" 42.0,\n",
" 1.0,\n",
" 12.0,\n",
" 0.0,\n",
" 2.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 4.0,\n",
" 0.0,\n",
" 121.0,\n",
" 1.0,\n",
" 0.0,\n",
" 4.0\n",
" ],\n",
" [\n",
" 2.0,\n",
" 29.0,\n",
" 3.0,\n",
" 2.0,\n",
" 98.0,\n",
" 0.0,\n",
" 6.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 3.0,\n",
" 0.0,\n",
" 1.0,\n",
" 0.0,\n",
" 21.0,\n",
" 1.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 7.0,\n",
" 0.0,\n",
" 1.0,\n",
" 6.0,\n",
" 0.0,\n",
" 409.0\n",
" ]\n",
" ]\n",
" },\n",
" \"logLoss\": 0.08260541,\n",
" \"confidenceMetrics\": [\n",
" {\n",
" \"precision\": 0.14285715,\n",
" \"precisionAt1\": 0.88776374,\n",
" \"recall\": 1.0,\n",
" \"f1ScoreAt1\": 0.88776374,\n",
" \"recallAt1\": 0.88776374,\n",
" \"f1Score\": 0.25\n",
" },\n",
" {\n",
" \"f1Score\": 0.8101266,\n",
" \"recall\": 0.9721519,\n",
" \"precision\": 0.69439423,\n",
" \"confidenceThreshold\": 0.05,\n",
" \"recallAt1\": 0.88776374,\n",
" \"precisionAt1\": 0.88776374,\n",
" \"f1ScoreAt1\": 0.88776374\n",
" },\n",
" \n",
" # REMOVED FOR BREVITY\n",
" \n",
" {\n",
" \"confidenceThreshold\": 1.0,\n",
" \"f1Score\": 0.0033698399,\n",
" \"f1ScoreAt1\": 0.0033698399,\n",
" \"precisionAt1\": 1.0,\n",
" \"precision\": 1.0,\n",
" \"recall\": 0.0016877637,\n",
" \"recallAt1\": 0.0016877637\n",
" }\n",
" ],\n",
" \"auPrc\": 0.95903283\n",
" },\n",
" \"createTime\": \"2021-02-26T06:07:48.967028Z\",\n",
" \"sliceDimensions\": [\n",
" \"annotationSpec\"\n",
" ]\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sIbqsuWeDdiJ"
},
"source": [
"## Make batch predictions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8USAjugOPmBE"
},
"source": [
"### Prepare files for batch prediction"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IHa-ducKPmBE"
},
"outputs": [],
"source": [
"test_item = ! gsutil cat $IMPORT_FILE | head -n1\n",
"test_item, test_label = str(test_item[0]).split(\",\")\n",
"\n",
"print(test_item, test_label)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "y0ThHBwoPmBF"
},
"source": [
"*Example output*:\n",
"```\n",
"I went on a successful date with someone I felt sympathy and connection with. affection\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_BMIZpOXPmBF"
},
"source": [
"### Make the batch input file\n",
"\n",
"Let's now make a batch input file, which you store in your local Cloud Storage bucket. The batch input file can be either CSV or JSONL. You will use JSONL in this tutorial. For JSONL file, you make one dictionary entry per line for each text file. The dictionary contains the key/value pairs:\n",
"\n",
"- `content`: The Cloud Storage path to the text file.\n",
"- `mimeType`: The content type. In our example, it is an `text/plain` file.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4ocY6QmHDdiJ"
},
"outputs": [],
"source": [
"import json\n",
"\n",
"import tensorflow as tf\n",
"\n",
"test_item_uri = \"gs://\" + BUCKET_NAME + \"/test.txt\"\n",
"with tf.io.gfile.GFile(test_item_uri, \"w\") as f:\n",
" f.write(test_item + \"\\n\")\n",
"\n",
"gcs_input_uri = \"gs://\" + BUCKET_NAME + \"/test.jsonl\"\n",
"with tf.io.gfile.GFile(gcs_input_uri, \"w\") as f:\n",
" data = {\"content\": test_item_uri, \"mime_type\": \"text/plain\"}\n",
" f.write(json.dumps(data) + \"\\n\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ztl9lP54PmBG"
},
"outputs": [],
"source": [
"! gsutil cat $gcs_input_uri\n",
"! gsutil cat $test_item_uri"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pAosq_OoPmBG"
},
"source": [
"*Example output*:\n",
"```\n",
"{\"content\": \"gs://migration-ucaip-trainingaip-20210226015238/test.txt\", \"mime_type\": \"text/plain\"}\n",
"I went on a successful date with someone I felt sympathy and connection with.\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YISzKhdUDdiJ"
},
"source": [
"### [projects.locations.batchPredictionJobs.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.batchPredictionJobs/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ozaMOwdNJjkT"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0ZSuOk8PDdiK"
},
"outputs": [],
"source": [
"batch_prediction_job = {\n",
" \"display_name\": \"happiness_\" + TIMESTAMP,\n",
" \"model\": model_id,\n",
" \"input_config\": {\n",
" \"instances_format\": \"jsonl\",\n",
" \"gcs_source\": {\"uris\": [gcs_input_uri]},\n",
" },\n",
" \"output_config\": {\n",
" \"predictions_format\": \"jsonl\",\n",
" \"gcs_destination\": {\n",
" \"output_uri_prefix\": \"gs://\" + f\"{BUCKET_NAME}/batch_output/\"\n",
" },\n",
" },\n",
" \"dedicated_resources\": {\n",
" \"machine_spec\": {\n",
" \"machine_type\": \"n1-standard-2\",\n",
" \"accelerator_count\": 0,\n",
" },\n",
" \"starting_replica_count\": 1,\n",
" \"max_replica_count\": 1,\n",
" },\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateBatchPredictionJobRequest(\n",
" parent=PARENT, batch_prediction_job=batch_prediction_job\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "swz5uddlPmBH"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"batchPredictionJob\": {\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/2369051733671280640\",\n",
" \"inputConfig\": {\n",
" \"instancesFormat\": \"jsonl\",\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210226015238/test.jsonl\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"predictionsFormat\": \"jsonl\",\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210226015238/batch_output/\"\n",
" }\n",
" },\n",
" \"dedicatedResources\": {\n",
" \"machineSpec\": {\n",
" \"machineType\": \"n1-standard-2\"\n",
" },\n",
" \"startingReplicaCount\": 1,\n",
" \"maxReplicaCount\": 1\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vHkuSZxkJjkT"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bvn9xCIZDdiK"
},
"outputs": [],
"source": [
"request = clients[\"job\"].create_batch_prediction_job(\n",
" parent=PARENT, batch_prediction_job=batch_prediction_job\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FLqkZMD2JjkT"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "PRO-_9tZDdiL"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gXCCM1C5PmBI"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/batchPredictionJobs/4770983263059574784\",\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/2369051733671280640\",\n",
" \"inputConfig\": {\n",
" \"instancesFormat\": \"jsonl\",\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210226015238/test.jsonl\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"predictionsFormat\": \"jsonl\",\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210226015238/batch_output/\"\n",
" }\n",
" },\n",
" \"state\": \"JOB_STATE_PENDING\",\n",
" \"completionStats\": {\n",
" \"incompleteCount\": \"-1\"\n",
" },\n",
" \"createTime\": \"2021-02-26T09:37:44.471843Z\",\n",
" \"updateTime\": \"2021-02-26T09:37:44.471843Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "-uhh056UPmBI"
},
"outputs": [],
"source": [
"# The fully qualified ID for the batch job\n",
"batch_job_id = request.name\n",
"# The short numeric ID for the batch job\n",
"batch_job_short_id = batch_job_id.split(\"/\")[-1]\n",
"\n",
"print(batch_job_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5UlgopM2DdiL"
},
"source": [
"### [projects.locations.batchPredictionJobs.get](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.batchPredictionJobs/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ONQ_S59sDdiM"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TmfmAJcyDdiM"
},
"outputs": [],
"source": [
"request = clients[\"job\"].get_batch_prediction_job(name=batch_job_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sXVZTJyUDdiM"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eeBVoWoADdiN"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Iqyjp1jBPmBJ"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/batchPredictionJobs/4770983263059574784\",\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/2369051733671280640\",\n",
" \"inputConfig\": {\n",
" \"instancesFormat\": \"jsonl\",\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210226015238/test.jsonl\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"predictionsFormat\": \"jsonl\",\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210226015238/batch_output/\"\n",
" }\n",
" },\n",
" \"state\": \"JOB_STATE_PENDING\",\n",
" \"completionStats\": {\n",
" \"incompleteCount\": \"-1\"\n",
" },\n",
" \"createTime\": \"2021-02-26T09:37:44.471843Z\",\n",
" \"updateTime\": \"2021-02-26T09:37:44.471843Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "batchpredictionjobs_get:migration,new,wait"
},
"outputs": [],
"source": [
"def get_latest_predictions(gcs_out_dir):\n",
" \"\"\" Get the latest prediction subfolder using the timestamp in the subfolder name\"\"\"\n",
" folders = !gsutil ls $gcs_out_dir\n",
" latest = \"\"\n",
" for folder in folders:\n",
" subfolder = folder.split(\"/\")[-2]\n",
" if subfolder.startswith(\"prediction-\"):\n",
" if subfolder > latest:\n",
" latest = folder[:-1]\n",
" return latest\n",
"\n",
"\n",
"while True:\n",
" response = clients[\"job\"].get_batch_prediction_job(name=batch_job_id)\n",
" if response.state != aip.JobState.JOB_STATE_SUCCEEDED:\n",
" print(\"The job has not completed:\", response.state)\n",
" if response.state == aip.JobState.JOB_STATE_FAILED:\n",
" break\n",
" else:\n",
" folder = get_latest_predictions(\n",
" response.output_config.gcs_destination.output_uri_prefix\n",
" )\n",
" ! gsutil ls $folder/prediction*.jsonl\n",
"\n",
" ! gsutil cat $folder/prediction*.jsonl\n",
" break\n",
" time.sleep(60)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "u3A8vXPAPmBK"
},
"source": [
"*Example output*:\n",
"```\n",
"gs://migration-ucaip-trainingaip-20210226015238/batch_output/prediction-happiness_20210226015238-2021-02-26T09:37:44.261133Z/predictions_00001.jsonl\n",
"{\"instance\":{\"content\":\"gs://migration-ucaip-trainingaip-20210226015238/test.txt\",\"mimeType\":\"text/plain\"},\"prediction\":{\"ids\":[\"8446203133482237952\",\"3834517115054850048\",\"1528674105841156096\",\"5563899371965120512\",\"952213353537732608\",\"3258056362751426560\",\"6140360124268544000\"],\"displayNames\":[\"affection\",\"bonding\",\"achievement\",\"enjoy_the_moment\",\"exercise\",\"leisure\",\"nature\"],\"confidences\":[0.9183423,0.045685068,0.024327256,0.0057157497,0.0040851077,0.0012627868,5.8173126E-4]}}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "k0vH7elnDdiN"
},
"source": [
"## Make online predictions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "COwVZtxhJjkW"
},
"source": [
"### [projects.locations.endpoints.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QjWCFUQADdiO"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZGavOazTDdiO"
},
"outputs": [],
"source": [
"endpoint = {\"display_name\": \"happiness_\" + TIMESTAMP}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateEndpointRequest(parent=PARENT, endpoint=endpoint).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HcwQyxKWPmBM"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"endpoint\": {\n",
" \"displayName\": \"happiness_20210226015238\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mLlY_jczDdiO"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_aEAOrzODdiO"
},
"outputs": [],
"source": [
"request = clients[\"endpoint\"].create_endpoint(parent=PARENT, endpoint=endpoint)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OG-RyJFeDdiP"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "p1Q2ZqOvDdiP"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Acb1LDrBPmBN"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/endpoints/7367713068517687296\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KcBsnK1vPmBN"
},
"outputs": [],
"source": [
"# The fully qualified ID for the endpoint\n",
"endpoint_id = result.name\n",
"# The short numeric ID for the endpoint\n",
"endpoint_short_id = endpoint_id.split(\"/\")[-1]\n",
"\n",
"print(endpoint_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gpnVJS3AJjkW"
},
"source": [
"### [projects.locations.endpoints.deployModel](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/deployModel)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NuN8rVoMDdiP"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "T8MSMXljDdiP"
},
"outputs": [],
"source": [
"deployed_model = {\n",
" \"model\": model_id,\n",
" \"display_name\": \"happiness_\" + TIMESTAMP,\n",
" \"automatic_resources\": {\"min_replica_count\": 1, \"max_replica_count\": 1},\n",
"}\n",
"\n",
"traffic_split = {\"0\": 100}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.DeployModelRequest(\n",
" endpoint=endpoint_id,\n",
" deployed_model=deployed_model,\n",
" traffic_split=traffic_split,\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gwh7ujzbPmBO"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"endpoint\": \"projects/116273516712/locations/us-central1/endpoints/7367713068517687296\",\n",
" \"deployedModel\": {\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/2369051733671280640\",\n",
" \"displayName\": \"happiness_20210226015238\",\n",
" \"automaticResources\": {\n",
" \"minReplicaCount\": 1,\n",
" \"maxReplicaCount\": 1\n",
" }\n",
" },\n",
" \"trafficSplit\": {\n",
" \"0\": 100\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Dh-h_nBZDdiQ"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wZVvs9ixDdiQ"
},
"outputs": [],
"source": [
"request = clients[\"endpoint\"].deploy_model(\n",
" endpoint=endpoint_id, deployed_model=deployed_model, traffic_split=traffic_split\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pu8ZfuUGDdiQ"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "o1TLdECDDdiQ"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5D0-_Md8PmBP"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"deployedModel\": {\n",
" \"id\": \"418518105996656640\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "deployed_model_id:migration,new,response"
},
"outputs": [],
"source": [
"# The unique ID for the deployed model\n",
"deployed_model_id = result.deployed_model.id\n",
"\n",
"print(deployed_model_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "I-IV01LtDdiQ"
},
"source": [
"### [projects.locations.endpoints.predict](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/predict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LcBcyGWEDdiQ"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LhRgG10QDdiR"
},
"outputs": [],
"source": [
"test_item = ! gsutil cat $IMPORT_FILE | head -n1\n",
"test_item, test_label = str(test_item[0]).split(\",\")\n",
"\n",
"instances_list = [{\"content\": test_item}]\n",
"instances = [json_format.ParseDict(s, Value()) for s in instances_list]\n",
"\n",
"request = aip.PredictRequest(\n",
" endpoint=endpoint_id,\n",
")\n",
"request.instances.append(instances)\n",
"\n",
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gpDpf_bqPmBR"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"endpoint\": \"projects/116273516712/locations/us-central1/endpoints/7367713068517687296\",\n",
" \"instances\": [\n",
" [\n",
" {\n",
" \"content\": \"I went on a successful date with someone I felt sympathy and connection with.\"\n",
" }\n",
" ]\n",
" ]\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "B59s9eGxDdiR"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6QSF5K1ZDdiR"
},
"outputs": [],
"source": [
"request = clients[\"prediction\"].predict(endpoint=endpoint_id, instances=instances)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ePJm-GgbDdiR"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "yeGeRM-UDdiR"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_3qjhEU4PmBS"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"predictions\": [\n",
" {\n",
" \"confidences\": [\n",
" 0.8867673277854919,\n",
" 0.024743923917412758,\n",
" 0.0034913308918476105,\n",
" 0.07936617732048035,\n",
" 0.0013463868526741862,\n",
" 0.0002393187169218436,\n",
" 0.0040455833077430725\n",
" ],\n",
" \"displayNames\": [\n",
" \"affection\",\n",
" \"achievement\",\n",
" \"enjoy_the_moment\",\n",
" \"bonding\",\n",
" \"leisure\",\n",
" \"nature\",\n",
" \"exercise\"\n",
" ],\n",
" \"ids\": [\n",
" \"8446203133482237952\",\n",
" \"1528674105841156096\",\n",
" \"5563899371965120512\",\n",
" \"3834517115054850048\",\n",
" \"3258056362751426560\",\n",
" \"6140360124268544000\",\n",
" \"952213353537732608\"\n",
" ]\n",
" }\n",
" ],\n",
" \"deployedModelId\": \"418518105996656640\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "endpoints_undeploymodel:migration,new"
},
"source": [
"### [projects.locations.endpoints.undeployModel](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/undeployModel)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "call:migration"
},
"source": [
"#### Call\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "endpoints_undeploymodel:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"endpoint\"].undeploy_model(\n",
" endpoint=endpoint_id, deployed_model_id=deployed_model_id, traffic_split={}\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "response:migration"
},
"source": [
"#### Response\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "print:migration,new,response"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "21vUY8uePmBU"
},
"source": [
"*Example output*:\n",
"```\n",
"{}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bQ-VVaSxJjkd"
},
"source": [
"# Cleaning up\r\n",
"\r\n",
"To clean up all GCP resources used in this project, you can [delete the GCP\r\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\r\n",
"\r\n",
"Otherwise, you can delete the individual resources you created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "SyXHVpimDdiS"
},
"outputs": [],
"source": [
"delete_dataset = True\n",
"delete_model = True\n",
"delete_endpoint = True\n",
"delete_pipeline = True\n",
"delete_batchjob = True\n",
"delete_bucket = True\n",
"\n",
"# Delete the dataset using the Vertex AI fully qualified identifier for the dataset\n",
"try:\n",
" if delete_dataset:\n",
" clients[\"dataset\"].delete_dataset(name=dataset_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the model using the Vertex AI fully qualified identifier for the model\n",
"try:\n",
" if delete_model:\n",
" clients[\"model\"].delete_model(name=model_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the endpoint using the Vertex AI fully qualified identifier for the endpoint\n",
"try:\n",
" if delete_endpoint:\n",
" clients[\"endpoint\"].delete_endpoint(name=endpoint_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the training pipeline using the Vertex AI fully qualified identifier for the training pipeline\n",
"try:\n",
" if delete_pipeline:\n",
" clients[\"pipeline\"].delete_training_pipeline(name=training_pipeline_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the batch job using the Vertex AI fully qualified identifier for the batch job\n",
"try:\n",
" if delete_batchjob:\n",
" clients[\"job\"].delete_batch_prediction_job(name=batch_job_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"if delete_bucket and \"BUCKET_NAME\" in globals():\n",
" ! gsutil rm -r gs://$BUCKET_NAME"
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [
"0yDWDaKwF48e",
"MDUAZaN3JjkL",
"hIHTX-pkJjkO",
"4x_t-MWnJjkQ"
],
"name": "UJ6 unified AutoML for natural language with Vertex AI Text Classification.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}